import { useBuildCSSStore, useThemeChangeStore } from "@/store";
import {
  computed,
  defineComponent,
  getCurrentInstance,
  onMounted,
  toRefs
} from "vue";

export default defineComponent({
  name: "FTIframe",
  props: {
    previewType: {
      type: String,
      default: ""
    }
  },
  setup(props) {
    // 标记iframe是否已加载
    let iframeLoaded=false;
    const instance = getCurrentInstance();
    const themeChange = useThemeChangeStore();
    const { previewType } = toRefs(props);
    const buildCSS = useBuildCSSStore();
    /**
     * 根据主题变更获取路由
     */
    const iframeUrl = computed(() => {
      return (
        document.getElementsByTagName("base")[0].href +
        previewType.value +
        "/" +
        themeChange.themeUrl
      );
    });
    /**
     * iframe通信
     */
    const iframeComm = (themeName:string='') => {
      
      const iframeDom = instance?.proxy?.$refs["iframe"] as HTMLIFrameElement;
      if (iframeDom) {
        console.log('-----------------------------------发出消息');
        iframeDom.contentWindow?.postMessage(
          {
            name: themeName||themeChange.themeName,
            size: themeChange.themeSize,
            color: themeChange.themeColor
          },
          iframeUrl.value
        );
      }
    };

    onMounted(() => {
      const iframeDom = instance?.proxy?.$refs["iframe"] as HTMLIFrameElement;
      if (iframeDom) {
        iframeDom.onload = (e) => {
          iframeLoaded=true;
          iframeComm();
        };
      }
      buildCSS.$subscribe((mutation, state) => {
        iframeLoaded&&iframeComm(state.name);
      });
    });

    return () => (
      <iframe
        ref="iframe"
        src={iframeUrl.value}
        style="width: 100%;height: 100%; border: 0;"
      ></iframe>
    );
  }
});
